IllegalCastException Exception

Caused by an attempt to recast an object and then sending it a message that its original type cannot handle.


Notes

An IllegalCastException error occurs when you attempt to cast an object to a different type and call a method or access a property belonging only to the original type. For example, if you recast a BevelButton as a PushButton (see the example below) and then call the Pushbutton's Push method, an IllegalCastException will occur because a BevelButton isn't a PushButton and happens not to have a Push method.


Example

This example attempts to cast a BevelButton as a PushButton then call the Push method of the PushButton class. This example assumes that there is a BevelButton called "BevelButton1" in the same window where this code is being called:

When you test this code in the IDE, execution will stop at the last line and display an IllegalCastException error in your Code editor. If you test the code in a standalone application, the application will display a generic error message and quit when the user clicks OK.

You can handle the error by adding an Exception block to your code:

Dim c as Control
c = BevelButton1
PushButton(c).Push
Exception err
If err IsA IllegalCastException then
  MsgBox "Trying to recast a BevelButton as PushButton!"
End if

The key difference is that, when the user accepts this dialog box, the application does not quit.


See Also

RuntimeException class; Function, Raise statements; Nil keyword; Exception, Try blocks.